<template>
  <div class="analysis-page">
    <el-card class="analysis-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <span>设备日志分析</span>
          <el-button type="primary" @click="refreshStatus" :loading="statusLoading">
            <el-icon><Refresh /></el-icon>
            刷新状态
          </el-button>
        </div>
      </template>

      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="120px"
        class="analysis-form"
      >
        <el-form-item label="设备SN" prop="deviceSn">
          <el-input
            v-model="form.deviceSn"
            placeholder="请输入设备SN号"
            clearable
            :disabled="analyzing"
          >
            <template #prepend>
              <el-icon><Mobile /></el-icon>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item label="手机号" prop="phone">
          <el-input
            v-model="form.phone"
            placeholder="请输入手机号"
            clearable
            :disabled="analyzing"
          >
            <template #prepend>
              <el-icon><Phone /></el-icon>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item label="用户名" prop="username">
          <el-input
            v-model="form.username"
            placeholder="请输入邮箱前缀"
            clearable
            :disabled="analyzing"
          >
            <template #prepend>
              <el-icon><User /></el-icon>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item label="密码" prop="password">
          <el-input
            v-model="form.password"
            type="password"
            placeholder="请输入密码"
            show-password
            clearable
            :disabled="analyzing"
          >
            <template #prepend>
              <el-icon><Lock /></el-icon>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item>
          <el-button
            type="primary"
            @click="startAnalysis"
            :loading="analyzing"
            :disabled="!isFormValid"
            size="large"
          >
            <el-icon><Search /></el-icon>
            {{ analyzing ? '分析中...' : '开始分析' }}
          </el-button>
          <el-button @click="resetForm" :disabled="analyzing">
            <el-icon><RefreshLeft /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 分析结果 -->
    <el-card v-if="analysisResult" class="result-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <span>分析结果</span>
          <el-tag :type="analysisResult.success ? 'success' : 'danger'">
            {{ analysisResult.success ? '成功' : '失败' }}
          </el-tag>
        </div>
      </template>

      <div v-if="analysisResult.success" class="success-content">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="设备SN">
            {{ analysisResult.deviceSn }}
          </el-descriptions-item>
          <el-descriptions-item label="分析时间">
            {{ formatTime(analysisResult.analysisTime) }}
          </el-descriptions-item>
          <el-descriptions-item label="输出目录" :span="2">
            <el-text type="info">{{ analysisResult.outputDirectory }}</el-text>
          </el-descriptions-item>
        </el-descriptions>

        <div v-if="analysisResult.generatedFiles && analysisResult.generatedFiles.length > 0" class="files-section">
          <h4>生成的文件：</h4>
          <el-tag
            v-for="file in analysisResult.generatedFiles"
            :key="file"
            class="file-tag"
            type="info"
          >
            {{ file }}
          </el-tag>
        </div>
      </div>

      <div v-else class="error-content">
        <el-alert
          :title="analysisResult.message"
          type="error"
          :description="analysisResult.errorDetails"
          show-icon
          :closable="false"
        />
      </div>
    </el-card>

    <!-- 进度显示 -->
    <el-card v-if="analyzing" class="progress-card" shadow="hover">
      <template #header>
        <span>分析进度</span>
      </template>
      <el-progress
        :percentage="progress"
        :status="progressStatus"
        :stroke-width="8"
      />
      <p class="progress-text">{{ progressText }}</p>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'

// 响应式数据
const formRef = ref()
const analyzing = ref(false)
const analysisResult = ref(null)
const progress = ref(0)
const progressStatus = ref('')
const progressText = ref('')

// 表单数据
const form = reactive({
  deviceSn: '',
  phone: '18650630979',
  username: 'fangxiang01',
  password: '1234589y.F'
})

// 表单验证规则
const rules = {
  deviceSn: [
    { required: true, message: '请输入设备SN', trigger: 'blur' },
    { 
      pattern: /^(7\d{17}|(A010|A020)\d{14})$/, 
      message: 'SN格式不正确，应为：以7开头的18位数字 或 以A010/A020开头的17位字符', 
      trigger: 'blur' 
    }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' }
  ],
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' }
  ]
}

// 计算属性
const isFormValid = computed(() => {
  return form.deviceSn && form.phone && form.username && form.password
})

// 方法
const startAnalysis = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    analyzing.value = true
    analysisResult.value = null
    progress.value = 0
    progressStatus.value = ''
    progressText.value = '准备开始分析...'
    
    // 模拟进度更新
    const progressInterval = setInterval(() => {
      if (progress.value < 90) {
        progress.value += Math.random() * 10
        updateProgressText()
      }
    }, 1000)
    
    try {
      const response = await axios.post('/api/analysis/device', form)
      analysisResult.value = response.data
      
      if (response.data.success) {
        progress.value = 100
        progressStatus.value = 'success'
        progressText.value = '分析完成！'
        ElMessage.success('设备日志分析成功')
      } else {
        progressStatus.value = 'exception'
        progressText.value = '分析失败'
        ElMessage.error(response.data.message)
      }
    } catch (error) {
      progressStatus.value = 'exception'
      progressText.value = '分析失败'
      ElMessage.error('分析过程中发生错误')
      
      if (error.response && error.response.data) {
        analysisResult.value = error.response.data
      }
    } finally {
      clearInterval(progressInterval)
      analyzing.value = false
    }
    
  } catch (error) {
    ElMessage.error('表单验证失败')
  }
}

const updateProgressText = () => {
  if (progress.value < 20) {
    progressText.value = '初始化浏览器...'
  } else if (progress.value < 40) {
    progressText.value = '登录系统...'
  } else if (progress.value < 60) {
    progressText.value = '下载日志文件...'
  } else if (progress.value < 80) {
    progressText.value = '解压并分析文件...'
  } else if (progress.value < 100) {
    progressText.value = '生成分析报告...'
  }
}

const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  analysisResult.value = null
  progress.value = 0
  progressStatus.value = ''
  progressText.value = ''
}

const formatTime = (timeString) => {
  if (!timeString) return ''
  return new Date(timeString).toLocaleString('zh-CN')
}
</script>

<style scoped>
.analysis-page {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.analysis-card,
.result-card,
.progress-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.analysis-form {
  max-width: 600px;
}

.success-content {
  margin-top: 20px;
}

.files-section {
  margin-top: 20px;
}

.file-tag {
  margin: 5px 5px 5px 0;
}

.error-content {
  margin-top: 20px;
}

.progress-text {
  text-align: center;
  margin-top: 10px;
  color: #666;
}
</style>
